import { loginAuth } from '@/utils/login';
import { getCache } from '@/utils/cache';
import { httpApi } from '@/utils/config';
export function request(config: any) {
	// 解构赋值
	let {
		data = {},
		method = 'POST'
	} = {
		...config
	};
	return new Promise((resolve, reject) => {
		let contentType = '';
		switch (method) {
			case 'POST':
				contentType = 'application/json';
				break;
			case 'GET':
				contentType = 'application/x-www-form-urlencoded';
				break;
			default:
				break;
		}
		uni.request({
			url: httpApi + '/bc-api' + config.url,
			header: {
				'Content-Type': contentType,
				token: getCache('token') ? getCache('token') : ''
			},
			method: method,
			data: {
				...data
			},
			success: (res: any) => {
				switch (res.statusCode) {
					case 200:
						if (res.data.code == 0) {
							resolve(res.data);
						} else if (res.data.code == 401 || res.data.code == 511) {
							loginAuth();
							reject(res.data);
						} else if ([500, 10001, 10002].includes(res.data.code)) {
							uni.showToast({
								icon: 'none',
								title: res.data.msg || '服务器异常',
								duration: 2000
							});
							reject(res.data);
						} else {
							reject(res.data);
						}
						break;
					case 500:
						uni.showToast({
							icon: 'none',
							title: '服务异常，请稍后重试',
							duration: 2000
						});
						break;
					default:
						break;
				}
			},
			fail: (err) => {
				reject(err);
			},
			complete: () => {}
		});
	});
}
